$(document).ready(function() {

  


    Chart.defaults.global.defaultFontColor = "#fff";

    /*
    * 扶翼今日数据统计分析
    */
    $('#fy-adv-tody-data').click(function(event){
           $('#section0').empty();
           $('#section1').empty();
           $('#section2').empty();
        if($(this).parent('li').is(".active")){
            console.log("return");
            return true;
            console.log("i should not get out");
        }else{
            /*清理当前的区域*/
            $('#section1').empty();
        }
        //点击事件
        console.log(1);
        $.ajax({
            url:"http://10.13.88.161:9000/fy/account/list?industry=%20&timeDiff=%20",
            dataType : "jsonp",
            jsonp: "callback",//服务端用于接收callback调用的function名的参数
            jsonpCallback:"success_jsonpCallback",//callback的function名称
            timeout:20000,
            success:function(data,status){
            //alert(status);
            console.log(status);
            }
        }) .done(function(data){
                console.log(data)
                var dataSet = data;

                var databox = $('<div class="box panel-blur" id="fytable1">' +
                                   '<div class="box-header">'+
                                       '<h3 class="box-title">今日广告主数据</h3>' +
                                       '<div class="box-tools pull-right">' +
                                           '<button type="button" class="btn bg-teal btn-sm" data-widget="collapse"><i class="fa fa-minus"></i>' +
                                           '</button>' +
                                           '<button type="button" class="btn bg-teal btn-sm" data-widget="remove"><i class="fa fa-times"></i>' +
                                           '</button>' +
                                       '</div>' +
                                   '</div>' +
                                   '<!-- /.box-header -->' +
                                   '<div class="box-body">' +
                                       '<table id="account-today" class="table table-bordered table-striped">' +
                                       '</table>' +
                                   '</div>' +
                                   '<!-- /.box-body -->' +
                               '</div>');
                $('#section0').append(databox);
                $("#account-today").DataTable( {
                    data: dataSet,
                    "scrollX": true,
                    columns: [
                        { title: "广告主" },
                        { title: "名称" },
                        { title: "曝光" },
                        { title: "点击." },
                        { title: "消耗（元）" },
                        { title: "CTR（‰）" }
                    ],
                  "initComplete": function () {
                        var api = this.api();
                        api.$('td').click( function () {
                            api.search( this.innerHTML ).draw();
                            var tr = $(this).parent('tr').first();
                            console.log(tr);
                            var tdhead = tr.children('td')[0];
                            var accountid = tdhead.innerHTML;
                            var accountname = accountid + tr.children('td')[1].innerHTML;
                            var table = $('#datatable-' + accountid)
                            if(table.length){
                                table.css("display", "block");
                            }else{
                                $('#section1').append('<div class="box panel-blur" id="datatable-' + accountid + '">' +
                                       '<div class="box-header">'+
                                           '<h3 class="box-title">广告主: ' + accountname + '数据</h3>' +
                                           '<div class="box-tools pull-right">' +
                                               '<button type="button" class="btn bg-teal btn-sm" data-widget="collapse"><i class="fa fa-minus"></i>' +
                                               '</button>' +
                                               '<button type="button" class="btn bg-teal btn-sm" data-widget="remove"><i class="fa fa-times"></i>' +
                                               '</button>' +
                                           '</div>' +
                                       '</div>' +
                                       '<!-- /.box-header -->' +
                                       '<div class="box-body">' +
                                           '<table id="table-' +accountid + '" class="table table-bordered table-striped">' +
                                           '</table>' +
                                       '</div>' +
                                       '<!-- /.box-body -->' +
                                   '</div>');
                                   $.ajax({
                                           url:"http://10.13.88.161:9000/fy/account/info",
                                           data: {accountid: accountid},
                                           timeout:60000,
                                           dataType:"json",
                                           success:function(data,status){
                                           //alert(status);
                                           console.log(status);
                                           }
                                       }) .done(function(data){
                                              $("#table-" +accountid).DataTable({
                                                  data: data,
                                                  "scrollX": true,
                                                  columns: [
                                                      { title: "广告组" },
                                                      { title: "投放单" },
                                                      { title: "创意"},
                                                      { title: "曝光" },
                                                      { title: "点击" },
                                                      { title: "消耗（元）" }
                                                  ]}
                                       )})
                                       .fail(function(xhr, status, errorThrown){
                                           alert("获取广告主" + accountname+ "详细信息错误 " + status);
                                           console.log("Error: " + errorThrown);
                                           console.log("Status: " + status);
                                       });
                                setMovBox();
                            }

                           var chart = $('#datachart-' + accountid);
                           if(chart.length){
                                chart.css("display", "block");
                           }else{
                                $('#section2').append('<!-- LINE CHART -->' +
                                    '<div class="box box-info panel-blur" id="datachart-'+ accountid+ '">' +
                                        '<div class="box-header with-border">' +
                                            '<h3 class="box-title">广告主 ' + accountname+ ' 今日数据分时图</h3>' +
                                            '<div class="box-tools pull-right">' +
                                                '<button type="button" class="btn btn-sm" data-widget="collapse"><i class="fa fa-minus"></i>' +
                                                '</button>' +
                                                '<button type="button" class="btn btn-sm" data-widget="remove"><i class="fa fa-times"></i></button>' +
                                            '</div>' +
                                        '</div>' +
                                        '<div class="box-body">' +
                                            '<div id="chart-' + accountid + '">' +
                                            '</div>' +
                                            '<div class="chart">' +
                                                '<canvas id="canvas-'+ accountid+'" width="400" height="400"></canvas>' +
                                            '</div>' +
                                        '</div>' +
                                        '<!-- /.box-body -->' +
                                    '</div>');
                                $.ajax({
                                        url:"http://10.13.88.161:9000/fy/account/hourstat?accountid=" + accountid,
                                        timeout:20000,
                                        dataType:"json",
                                        success:function(data,status){
        //                                    alert(status);
                                            console.log(status);
                                        }
                                }) .done(function(data){
                                          console.log(data)
                                         var chart_canvas_id = 'canvas-' + accountid;
                                            var config = {
                                                type: 'line',
                                                data: {
                                                    labels: data.time,
                                                    datasets: [{
                                                        label: "pv",
                                                        backgroundColor: "rgba(155,255,230,1)",
                                                        borderColor: "rgba(155,255,230,1)",
                                                        data: data.pv,
                                                        fill: false,
                                                    }, {
                                                        label: "click",
                                                        fill: false,
                                                        backgroundColor: "rgba(234,133,255,1)",
                                                        borderColor: "rgba(234,133,255,1)",
                                                        data: data.click,
                                                    }, {
                                                        label: "bill",
                                                        fill: false,
                                                        backgroundColor: "rgba(255,255,255,1)",
                                                        borderColor: "rgba(255,255,255,1)",
                                                        data: data.bill,
                                                    }]
                                                },
                                                options: {
                                                    responsive: true,
                                                    title:{
                                                        display:false,
                                                        text:'广告主 ' + accountname+ ' 今日数据分时图'
                                                    },
                                                    tooltips: {
                                                        mode: 'index',
                                                        intersect: false,
                                                    },
                                                    hover: {
                                                        mode: 'nearest',
                                                        intersect: false
                                                    },
                                                    scales: {
                                                        xAxes: [{
                                                            display: true,
                                                            scaleLabel: {
                                                                display: false,
                                                                labelString: 'Hour'
                                                            }
                                                        }],
                                                        yAxes: [{
                                                            display: true,
                                                            scaleLabel: {
                                                                display: false,
                                                                labelString: 'Value'
                                                            }
                                                        }]
                                                    }
                                                }
                                            };
                                            var ctx = document.getElementById(chart_canvas_id).getContext("2d");
                                            window.myLine = new Chart(ctx, config);
                                           })
                                       .fail(function(xhr, status, errorThrown){
                                           alert("获取广告主" + accountname +"分时信息错误 " + status);
                                               console.log("Error: " + errorThrown);
                                               console.log("Status: " + status);
                                       });
                           }
                        });
                    }
                });
             })
        .fail(function(xhr, status, errorThrown){
            alert("获取广告主信息错误 " + status);
                console.log("Error: " + errorThrown);
                console.log("Status: " + status);
        });
    });


   /*
    * 扶翼今日行业分析
    */
    $('#fy-indus-tody-data').click(function(event){
        if($(this).parent('li').is(".active")){
            console.log("return");
            return true;
        }else{
            /*清理当前的区域*/
            $('#section0').empty();
            $('#section1').empty();
            $('#section2').empty();
        }
        //app 和 非APP 的数据获取
        $.ajax({
            url: "http://10.13.88.161:9000/fy/industry/first",
            dataType: 'json',
            timeout: 20000,
            success: function(data, status){console.log(status);}
        })
        .done(function(data){
            console.log(data);

            $('#section1').append('<div class="box panel-blur" id="fy-indus1-box-tody">' +
                 '<div class="box-header">'+
                     '<h3 class="box-title">一级行业数据分析</h3>' +
                     '<div class="box-tools pull-right">' +
                         '<button type="button" class="btn bg-teal btn-sm" data-widget="collapse"><i class="fa fa-minus"></i>' +
                         '</button>' +
                         '<button type="button" class="btn bg-teal btn-sm" data-widget="remove"><i class="fa fa-times"></i>' +
                         '</button>' +
                     '</div>' +
                 '</div>' +
                 '<!-- /.box-header -->' +
                 '<div class="box-body">' +
                     '<div class="chart">' +
                         '<canvas id="canvas-fy-indus1-tody" width="400" height="400"></canvas>' +
                     '</div>' +
                 '</div>' +
                 '<!-- /.box-body -->' +
                 '<div class="box-footer">' +
                  '<div class="btn-group">' +
                      '<button type="button" class="btn btn-block btn-info indus" data-indus="APP" data-subid="app">APP行业数据分析</button>' +
                      '<button type="button" class="btn btn-block btn-info indus" data-indus="非APP" data-subid="non-app">非APP行业数据分析</button>' +

                  '</div>' +
                '</div>' +
             '</div>');
            setMovBox();
           /**绘制pie图*/
           var config = {
                type: 'pie',
                data: data,
                options: {
                    responsive: true,
                    tooltips: {
                        callbacks: {
                            beforeLabel: function(tooltipItem, data){
                                var index = tooltipItem.datasetIndex;
                                var label = data.datasets[index].label;
                                console.log(tooltipItem);
                                console.log(label);
                                return label;

                            }
                        }
                    }

                }
            };

            var ctx = document.getElementById("canvas-fy-indus1-tody").getContext("2d");
            window.myPie = new Chart(ctx, config);

            /* 柱状图显示*/
           $('#fy-indus1-box-tody-bar-btn').click(function(event){
                $('#section1').append('<div class="box panel-blur" id="fy-indus1-box-tody-bar-box">' +
                     '<div class="box-header">'+
                         '<h3 class="box-title">一级行业数据分析柱状图</h3>' +
                         '<div class="box-tools pull-right">' +
                             '<button type="button" class="btn bg-teal btn-sm" data-widget="collapse"><i class="fa fa-minus"></i>' +
                             '</button>' +
                             '<button type="button" class="btn bg-teal btn-sm" data-widget="remove"><i class="fa fa-times"></i>' +
                             '</button>' +
                         '</div>' +
                     '</div>' +
                     '<!-- /.box-header -->' +
                     '<div class="box-body">' +
                         '<div class="chart">' +
                             '<canvas id="canvas-fy-indus1-box-tody-bar" width="400" height="400"></canvas>' +
                         '</div>' +
                     '</div>' +
                     '<!-- /.box-body -->' +
                     '<div class="box-footer">' +
                    '</div>' +
                 '</div>');

                 /*绘制柱状图*/


           })
           /*一级行业详细数据*/
           $('button.indus').click(function(event){
                var param = $(this).data('indus');
                var subid = $(this).data('subid');
                var text = $(this).text();
                $.ajax({
                    url: "http://10.13.88.161:9000/fy/industry/second",
                    data: {parentIndus: param},
                    success: function(data, status){console.log(status);}
                })
                .done(function(data){
                    /*绘制柱状图*/
                    $('#section1').append('<div class="box panel-blur" id="fy-'+ subid +'-indus2-box-pie-tody">' +
                         '<div class="box-header">'+
                             '<h3 class="box-title">'+ param +'行业数据分析</h3>' +
                             '<div class="box-tools pull-right">' +
                                 '<button type="button" class="btn bg-teal btn-sm" data-widget="collapse"><i class="fa fa-minus"></i>' +
                                 '</button>' +
                                 '<button type="button" class="btn bg-teal btn-sm" data-widget="remove"><i class="fa fa-times"></i>' +
                                 '</button>' +
                             '</div>' +
                         '</div>' +
                         '<!-- /.box-header -->' +
                         '<div class="box-body">' +
                             '<div class="chart">' +
                                 '<canvas id="canvas-fy-'+ subid +'-indus2-pie-tody" width="400" height="400"></canvas>' +
                             '</div>' +
                         '</div>' +
                         '<!-- /.box-body -->' +
                     '</div>');

                    /**绘制数据*/

                    var config = {
                        type: 'bar',
                        data: data.barData,
                        options: {
                            responsive: true,
                            legend: {
                                position: 'top',
                            },
                            title: {
                                display: true,
                                text: 'APP行业分布'
                            }
                        }
                    };
                    var ctx = document.getElementById("canvas-fy-"+ subid +"-indus2-pie-tody").getContext("2d");
                    var pie = new Chart(ctx, config);

                    /*绘制饼图*/
                    $('#section1').append('<div class="box panel-blur" id="fy-'+ subid +'-indus2-box-bar-tody">' +
                         '<div class="box-header">'+
                             '<h3 class="box-title">'+ param +'行业数据分析</h3>' +
                             '<div class="box-tools pull-right">' +
                                 '<button type="button" class="btn bg-teal btn-sm" data-widget="collapse"><i class="fa fa-minus"></i>' +
                                 '</button>' +
                                 '<button type="button" class="btn bg-teal btn-sm" data-widget="remove"><i class="fa fa-times"></i>' +
                                 '</button>' +
                             '</div>' +
                         '</div>' +
                         '<!-- /.box-header -->' +
                         '<div class="box-body">' +
                             '<div class="chart">' +
                                 '<canvas id="canvas-fy-'+ subid +'-indus2-bar-tody" width="400" height="400"></canvas>' +
                             '</div>' +
                         '</div>' +
                         '<!-- /.box-body -->' +
                     '</div>');

                    var config = {
                        type: 'pie',
                        data: data.pieData,
                        options: {
                            responsive: true,
                            legend: {
                                display: true,
                            },
                            tooltips: {
                                enabled: true,
                            }
                        }
                    };
                    var ctx = document.getElementById("canvas-fy-"+ subid +"-indus2-bar-tody").getContext("2d");
                    window.myPie = new Chart(ctx, config);
                })
           })
        });
    })

   /*
    * 扶翼资源统计分析
    */
    $('#fy-res-tody-data').click(function(event){
        var id = 'fy-res-tody-chart';
        $('#section0').empty();
        $('#section1').empty();
        $('#section2').empty();
        var boxid = 'box-' + id;
        if(boxExist(boxid)){boxDisplay(boxid);}else{
            addBox("section2", id, "广告流量分类统计", 2, "", "", "app");
            $.ajax({
                url: "http://10.13.88.161:9000/fy/resource/today",
                timeout: 20000,
                dataType: 'json'
            })
            .done(function(json){
                Highcharts.chart('hicharts-' + id, {
                    chart: {
                      type: 'pie'
                    },
                    title: {
                      text: '各流量分类今日曝光数'
                    },
                    subtitle: {
                      text: '点击切片查看详细信息'
                    },
                    plotOptions: {
                      series: {
                        dataLabels: {
                          enabled: true,
                          format: '{point.name}: {point.y}'
                        }
                      }
                    },

                    tooltip: {
                      headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
                      pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y}</b> of total<br/>'
                    },
                    series: json.pieData.series,
                    drilldown: json.pieData.drilldown
                  });

                tableid = 'fy-res-tody-table'
                addBox('section1', tableid, "各流量分类今日曝光数", 0, "", "", "app");
                console.log(json.tableData)
                $("#table-" + tableid).DataTable({
                data: json.tableData.data,
                "scrollX": true,
                columns: json.tableData.columns})
            })
            .fail(function(xhr, status, errorThrown){
                alert("获取资源信息错误" + status);
                    console.log("Error: " + errorThrown);
                    console.log("Status: " + status);
                $('#section0').empty();
            });
        }
    })
   /*
    * APP网络环境分析
    */
    $('#fy-net-tody-data').click(function(event){
        $('#section0').empty();
        $('#section1').empty();
        $('#section2').empty();
        var id = "fy-net-tody-app-data"
        var boxid = "box-" + id;
        if(boxExist(boxid)){boxDisplay(boxid);}else{
            addBox('section2', id, "APP网络环境今日曝光数", 1, "", "", "app");
            $.ajax({
                url: "http://10.13.88.161:9000/fy/net/today",
                timeout: 20000,
                dataType:"json"
            })
            .done(function(data){
                console.log(data);
                var canvasid = "canvas-" + id;
                var config = {
                    type: 'bar',
                    data: data.barData,
                    options: {
                        title:{
                            display:false,
                            text:"Chart.js Bar Chart - Stacked"
                        },
                        tooltips: {
                            mode: 'index',
                            intersect: false
                        },
                        responsive: true
                    }
                };
                var ctx = document.getElementById(canvasid).getContext("2d");
                var handle = new Chart(ctx, config);

                /*绘制饼图*/
                var pieid = "pie-fy-net-tody-app-data"
                var pieboxid = "box-" + pieid;
                addBox('section2', pieid, "APP网络环境今日曝光百分比", 3, "", "", "app");
                var pieconfig = {
                    type: 'pie',
                    data: data.pieData,
                    options: {
                        responsive: true,
                        legend: {
                            display: true,
                        },
                        tooltips: {
                            enabled: true,
                        }
                    }
                };
                var piectx = document.getElementById("canvas-"+ pieid).getContext("2d");
                window.myPie = new Chart(piectx, pieconfig);
            })
            .fail(function(xhr, status, errorThrown){
                alert("获取网络环境今日信息错误 " + status);
                    console.log("Error: " + errorThrown);
                    console.log("Status: " + status);
            });
        }
        var hourid = "fy-net-tody-hour-data"
        var hourboxid = "box-" + hourid
        if(boxExist(hourboxid)){boxDisplay(boxid);}else{
            addBox('section1', hourid, "APP网络环境今日分时曝光数", 1, "", "", "app");
            $.ajax({
                url: "http://10.13.88.161:9000/fy/nethour/today",
                timeout: 20000,
                dataType:"json"
            })
            .done(function(data){
                console.log(data);
                var config = {
                    type: 'bar',
                    data: data,
                    options: {
                        title:{
                            display:false,
                            text:"Chart.js Bar Chart - Stacked"
                        },
                        tooltips: {
                            mode: 'index',
                            intersect: false
                        },
                        responsive: true,
                        scales: {
                            xAxes: [{
                                stacked: true,
                            }],
                            yAxes: [{
                                stacked: true
                            }]
                        }
                    }
                };
                var ctx = document.getElementById("canvas-"+ hourid).getContext("2d");
                var handle = new Chart(ctx, config);
            })
            .fail(function(xhr, status, errorThrown){
                alert("获取网络环境今日信息错误 " + status);
                    console.log("Error: " + errorThrown);
                    console.log("Status: " + status);
            });
        }
    })


   /*
    * 手机OS统计分析
    */
    $('#fy-os-tody-data').click(function(event){
        $('#section0').empty();
        $('#section1').empty();
        $('#section2').empty();
        var id = "fy-net-tody-app-data"
        var boxid = "box-" + id;
        if(boxExist(boxid)){boxDisplay(boxid);}else{
            addBox('section1', id, "手机OS今日曝光数", 1, "", "", "app");
            $.ajax({
                url: "http://10.13.88.161:9000/fy/os/today",
                timeout: 20000,
                dataType:"json"
            })
            .done(function(data){
                console.log(data);
                var canvasid = "canvas-" + id;
                var config = {
                    type: 'bar',
                    data: data.barData,
                    options: {
                        title:{
                            display:false,
                            text:"Chart.js Bar Chart - Stacked"
                        },
                        tooltips: {
                            mode: 'index',
                            intersect: false
                        },
                        responsive: true
                    }
                };
                var ctx = document.getElementById(canvasid).getContext("2d");
                var handle = new Chart(ctx, config);

                var pieid = "pie-fy-os-tody-app-data"
                var pieboxid = "box-" + pieid;
                addBox('section2', pieid, "手机OS今日曝光百分比", 3, "", "", "app");
                    /*绘制饼图*/
                    var pieconfig = {
                        type: 'pie',
                        data: data.pieData,
                        options: {
                            responsive: true,
                            legend: {
                                display: true,
                            },
                            tooltips: {
                                enabled: true,
                            }
                        }
                    };
                    var piectx = document.getElementById("canvas-"+ pieid).getContext("2d");
                    window.myPie = new Chart(piectx, pieconfig);
            })
            .fail(function(xhr, status, errorThrown){
                alert("获取手机OS今日信息错误 " + status);
                    console.log("Error: " + errorThrown);
                    console.log("Status: " + status);
            });
        }
    })

    //扶翼代理商信息查询
    $('#fy-adunit-creative-info').click(function(event){
       $('#section0').empty();
       $('#section1').empty();
       $('#section2').empty();

        $('#section0').append(
            '<div class="row">' +
                '<div class="col-md-4">' +
                    '<!-- search form -->' +
                    '<form action="#" method="get" class="sidebar-form">' +
                        '<div class="input-group">' +
                            '<input type="text" name="q" id="search-adunitid-fy-creative-input" class="form-control" placeholder="输入广告位">' +
                          '<span class="input-group-btn">' +
                            '<button type="submit" name="search" id="search-adunitid-fy-creative-btn" class="btn btn-flat"><i class="fa fa-search"></i>' +
                            '</button>' +
                          '</span>' +
                        '</div>' +
                    '</form>' +
                '</div>' +
            '</div>'
        );
        $('#search-adunitid-fy-creative-btn').click(function(event){
            console.log('search-adunitid-fy-creative-btn clicked');
            var adunitid = $('#search-adunitid-fy-creative-input').val();
            $.ajax({
                url: 'http://10.13.88.161:9000/sax/isvalidadunit',
                data: {id: adunitid},
                timeout: 20000
            })
            .done(function(data){
                if(data == "true"){
                    var id = adunitid + "-product2-creative-info"
                    addBox('section0', id, "各行业创意信息", 0, "", "", "app");
                    $.ajax({
                        url: "http://10.13.88.161:9000/fyproductcreativeinfo",
                        data: {adunitid: adunitid},
                        timeout: 2000,
                        dataType:"json"
                    })
                    .done(function(json){
                        console.log(json);
                        $('#table-' + id).DataTable({
                            data: json.data,
                            "scrollX": true,
                            columns: json.columns,
                            "initComplete": function(){
                                var api = this.api();
                                api.$('td').click( function () {
                                    api.search( this.innerHTML ).draw();
                                    var tr = $(this).parent('tr').first();
                                    console.log(tr);
                                    var tdhead = tr.children('td')[0];
                                    var industry = tdhead.innerHTML;
                                    var boxid = adunitid + industry + "-industry2-ad-detail"
                                    if(boxExist('box-' + boxid)){boxDisplay('box-' + boxid);}else{
                                        addBox('section0', boxid, industry + "行业详细创意信息", 0, "", "", "app");
                                        $.ajax({
                                            url: 'http://10.13.88.161:9000/fyinduscreativedetail',
                                            data: {adunitid: adunitid,
                                                  industry: industry},
                                            timeout: 20000,
                                            dataType:"json"
                                        })
                                        .done(function(json){
                                            console.log(json);
                                            $('#table-' + boxid).DataTable({
                                                data: json.data,
                                                "scrollX": true,
                                                columns: json.columns
                                            })
                                        })
                                        .fail(function(xhr, status, errorThrown){
                                            alert("获取行业详细创意信息失败" + status);
                                                console.log("Error: " + errorThrown);
                                                console.log("Status: " + status);
                                            $('#section1').empty();
                                        });
                                        setMovBox();
                                    }
                                });
                            }
                        });
                    })
                }else{
                    alert(adunitid + " 不是有效广告位");
                }
            })
            .fail(function(xhr, status, errorThrown){
                alert("校验广告失败" + status);
                    console.log("Error: " + errorThrown);
                    console.log("Status: " + status);
                $('#section0').empty();
            });
            event.preventDefault();
        })
    })

   /*
    *  扶翼qps数据实时展示
    */
    $('#fy-qps').click(function(event){
        if($(this).parent('li').is('.active')){
          return true;
        }else{
            /*清理当前区域*/
            var chart = $('#datachart-fyqps')
            if(chart.length){
                chart.css("display", "block");
            }else{
            $('#section0').append('<!-- LINE CHART -->' +
                '<div class="box box-info panel-blur" id="datachart-fyqps">' +
                    '<div class="box-header with-border">' +
                        '<h3 class="box-title">扶翼 广告请求qps状态实时数据</h3>' +
                        '<div class="box-tools pull-right">' +
                            '<button id="qps-refresh" type="button" class="btn btn-sm"><i class="fa fa-refresh"></i>' +
                            '<button type="button" class="btn btn-sm" data-widget="collapse"><i class="fa fa-minus"></i>' +
                            '</button>' +
                            '<button type="button" class="btn btn-sm" data-widget="remove"><i class="fa fa-times"></i></button>' +
                        '</div>' +
                    '</div>' +
                    '<div class="box-body">' +
                        '<div id="chart-fyqps">' +
                        '</div>' +
                        '<div class="chart">' +
                            '<canvas id="canvas-fyqps" width="200" height="100"></canvas>' +
                        '</div>' +
                    '</div>' +
                    '<div class="box-footer">' +
                         '<div class="form-group">' +
                             '<label>选择时间区间</label>' +
                             '<select id="qps-time-range-sel" class="form-control select2" style="width: 100%;">' +
                               '<option value="now()+-+15m" selected="selected">过去15m</option>' +
                               '<option value="now()+-+1h">过去1h</option>' +
                               '<option value="now()+-+2h">过去2h</option>' +
                               '<option value="now()+-+3h">过去3h</option>' +
                               '<option value="now()+-+4h">过去4h</option>' +
                               '<option value="now()+-+6h">过去6h</option>' +
                               '<option value="now()+-+12h">过去12h</option>' +
                             '</select>' +
                         '</div>' +
                    '</div>' +
                    '<!-- /.box-body -->' +
                '</div>');

                $('#qps-time-range-sel').select2({
                    minimumResultsForSearch: Infinity
                });


                /*获取扶翼的qps数据并进行绘制*/
                $.ajax({
                    url:"http://10.13.88.161:9000/fyqps",
                    data: {timeRange: "now()+-+15m"},
                    timeout:20000,
                    dataType:"json",
                    success:function(data,status){
                        //alert(status);
                        console.log(status);
                    }
                }).done(function(json){

                    Chart.defaults.global.defaultFontColor = "#fff";

                    var config = {
                        type: 'line',
                        data: {
                            labels: json.labels,
                            datasets: json.datasets,
                        },
                        options: {
                            title:{
                                text: "Chart.js Time Scale"
                            },
                            scales: {
                                xAxes: [{
                                    type: "time",
                                    time: {
                                        format: json.dateFormat,
                                        // round: 'day'
                                        tooltipFormat: 'll HH:mm'
                                    },
                                    scaleLabel: {
                                        display: false,
                                        labelString: 'Date'
                                    },
                                    ticks: {
                                        fontColor: "#fff"
                                    }
                                }, ],
                                yAxes: [{
                                    scaleLabel: {
                                        display: false,
                                        labelString: 'value'
                                    },
                                    ticks: {
                                        fontColor: "#fff"
                                    }
                                }]


                            },
                            responsive: true,
                            fontColor: '#fff',
                            tooltips: {
                                position: 'average',
                                mode: 'index',
                                intersect: false,
                            }
                        }
                    };
                    var ctx = document.getElementById("canvas-fyqps").getContext("2d");
                    var qpscharthanle = new Chart(ctx, config);
                    $('#qps-refresh').click(function(event){
                        $.ajax({
                            url:"http://10.13.88.161:9000/fyqps",
                            data: {timeRange: $('#qps-time-range-sel').val()},
                            timeout:20000,
                            dataType:"json",
                            success:function(data,status){
                                //alert(status);
                                console.log(status);
                            }
                        }).done(function(json){
                            config.data.datasets = json.datasets;
                            qpscharthanle.update();
                        });
                    })

                    $('#qps-time-range-sel').on("select2:select", function (e) {
                        var timeRange = $(this).val();
                        console.log(timeRange);
                        $.ajax({
                            url:"http://10.13.88.161:9000/fyqps",
                            data: {timeRange: timeRange},
                            timeout:20000,
                            dataType:"json",
                            success:function(data,status){
                                //alert(status);
                                console.log(status);
                            }
                        }).done(function(json){
                            config.data.datasets = json.datasets;
                            qpscharthanle.update();
                        });

                    });
                })
                .fail(function(xhr, status, errorThrown){
                    alert("获取广告主信息错误 " + status);
                        console.log("Error: " + errorThrown);
                        console.log("Status: " + status);
                    $('#section0').empty();
                });

            }

        }
    })


   /*
    * 广告主数据历史数据
    */
    $('#fy-adv-his-data').click(function(event){
        return true;
    })

   /*
    * 行业历史数据分析
    */
    $('#fy-indus-his-data').click(function(event){
       $('#section0').empty();
       $('#section1').empty();
       $('#section2').empty();
       var id = "fy-indus-his-app-data"
       var boxid = "box-" + id;
       if(boxExist(boxid)){boxDisplay(boxid);}else{

            function cb(start, end) {
                $('#daterange-btn1 span').html(start.format('YYYY-MM-DD') + ' - ' + end.format('YYYY-MM-DD'));
            }
            var contenthead ='<form>' +
                               '<label class="radio-inline">' +
                                 '<input type="radio" name="appradio" id="radio-pv" value="pv" checked> 曝光' +
                               '</label>' +
                               '<label class="radio-inline">' +
                                 '<input type="radio" name="appradio" id="radio-click" value="click"> 点击' +
                               '</label>' +
                               '<label class="radio-inline">' +
                                 '<input type="radio" name="appradio" id="radio-bill" value="bill"> 消耗' +
                               '</label>' +
                             '</form>'

            var footer = '<div class="box-footer">' +
                              '<div class="form-group">' +
                                  '<label>Date range button:</label>' +
                                  '<div class="input-group">' +
                                    '<button type="button" class="btn btn-default pull-right" id="daterange-btn1">' +
                                      '<span>' +
                                        '<i class="fa fa-calendar"></i> Date range picker' +
                                      '</span>' +
                                      '<i class="fa fa-caret-down"></i>' +
                                    '</button>' +
                                  '</div>' +
                                '</div>' +
                          '</div>'
            addBox("section1", id, "APP类广告主数据分析", 1, footer, contenthead, "app");
            $('#daterange-btn1').daterangepicker(
               {
                 ranges: {
                   'Today': [moment(), moment()],
                   'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                   'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                   'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                   'This Month': [moment().startOf('month'), moment().endOf('month')],
                   'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
                 },
                 startDate: moment().subtract(6, 'days'),
                 endDate: moment()
               },
               cb
           );
            var start = moment().subtract(6, 'days');
            var end = moment();
            cb(start, end);

            $.ajax({
                url: "http://10.13.88.161:9000/fy/industry/history",
                data: {
                    industry: "APP",
                    interval: "1d",
                    from: start.format('YYYY-MM-DD'),
                    to: end.format('YYYY-MM-DD')
                },
                timeout: 20000
            })
            .done(function(data){
                console.log(data);
                var canvasid = "canvas-" + id;
                var config = {
                    type: 'bar',
                    data: data.pvdatasets,
                    options: {
                        title:{
                            display:true,
                            text:"Chart.js Bar Chart - Stacked"
                        },
                        tooltips: {
                            mode: 'index',
                            intersect: false
                        },
                        responsive: true,
                        scales: {
                            xAxes: [{
                                stacked: true,
                            }],
                            yAxes: [{
                                stacked: true
                            }]
                        }
                    }
                };
                var ctx = document.getElementById(canvasid).getContext("2d");
                var handle = new Chart(ctx, config);

                 $( "input[name='appradio']").change(function(){
                    var set = $(this).val();
                    console.log(set);
                    if(set == "pv"){
                        config.data = data.pvdatasets;
                    }else if(set == 'click'){
                        config.data = data.clickdatasets;
                    }else if(set == "bill"){
                        config.data = data.billdatasets;
                    }
                    handle.update()
                });
            })
       }

       /*非APP广告主数据分析*/
        var id2 = "fy-indus-his-no-app-data"
        var boxid2 = "box-" + id2;
        if(boxExist(boxid2)){boxDisplay(boxid2);}else{
           function cb(start, end) {
               $('#daterange-btn2 span').html(start.format('YYYY-MM-DD') + ' - ' + end.format('YYYY-MM-DD'));
           }

           var contenthead ='<form>' +
                          '<label class="radio-inline">' +
                            '<input type="radio" name="nonappradio" id="radio-pv" value="pv" checked> 曝光' +
                          '</label>' +
                          '<label class="radio-inline">' +
                            '<input type="radio" name="nonappradio" id="radio-click" value="click"> 点击' +
                          '</label>' +
                          '<label class="radio-inline">' +
                            '<input type="radio" name="nonappradio" id="radio-bill" value="bill"> 消耗' +
                          '</label>' +
                        '</form>'
           var footer = '<div class="box-footer">' +
                             '<div class="form-group">' +
                                 '<label>Date range button:</label>' +
                                 '<div class="input-group">' +
                                   '<button type="button" class="btn btn-default pull-right" id="daterange-btn2">' +
                                     '<span>' +
                                       '<i class="fa fa-calendar"></i> Date range picker' +
                                     '</span>' +
                                     '<i class="fa fa-caret-down"></i>' +
                                   '</button>' +
                                 '</div>' +
                               '</div>' +
                         '</div>'

           addBox("section1", id2, "非APP类广告主数据分析", 1, footer, contenthead, "app");
           $('#daterange-btn2').daterangepicker(
               {
                 ranges: {
                   'Today': [moment(), moment()],
                   'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                   'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                   'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                   'This Month': [moment().startOf('month'), moment().endOf('month')],
                   'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
                 },
                 startDate: moment().subtract(6, 'days'),
                 endDate: moment()
               },
               cb
           );
           var start = moment().subtract(6, 'days');
           var end = moment();
           cb(start, end);
           $.ajax({
               url: "http://10.13.88.161:9000/fy/industry/history",
               data: {
                   industry: "非APP",
                   interval: "1d",
                   from: start.format('YYYY-MM-DD'),
                   to: end.format('YYYY-MM-DD')
               },
               timeout: 20000
           })
           .done(function(data){
                console.log(data);
                var canvasid = "canvas-" + id2;
                var config = {
                    type: 'bar',
                    data: data.pvdatasets,
                    options: {
                        title:{
                            display:true,
                            text:"Chart.js Bar Chart - Stacked"
                        },
                        tooltips: {
                            mode: 'index',
                            intersect: false
                        },
                        responsive: true,
                        scales: {
                            xAxes: [{
                                stacked: true,
                            }],
                            yAxes: [{
                                stacked: true
                            }]
                        }
                    }
                };
                var ctx = document.getElementById(canvasid).getContext("2d");
                var handle = new Chart(ctx, config);

                 $( "input[name='nonappradio']").change(function(){
                        var set = $(this).val();
                        console.log(set);
                        if(set == "pv"){
                            config.data = data.pvdatasets;
                        }else if(set == 'click'){
                            config.data = data.clickdatasets;
                        }else if(set == "bill"){
                            config.data = data.billdatasets;
                        }
                        handle.update()
                    });
           })
        }
    })


  /*
   * 资源分类广告查询
   */
   $('#res-adunits').click(function(event){
        $('#section0').empty();
        $('#section1').empty();
        $('#section2').empty();

        $('#section0').append(
            '<div class="col-md-3">' +
                '<div id="res-tree" class="pre-scrollable"></div>' +
            '</div>' +
            '<div class="col-md-8" id="seciont0-col-8">' +
            '</div>'
        )

        $.ajax({
            type:"GET",
            url: "http://10.13.88.161:9000/adunitsinfo",
            dataType: 'json',
            timeout: 10000
        }).done(function(json){
            $('#res-tree').treeview({
                data: json,
                showTags: true,
                showIcon: true,
                enableLinks: true,
                onNodeSelected: function(event, data) {
                   console.log(data);
                   var labels = data.labels.join(',');
                   var days7 = moment(0, "HH").subtract(6, "day").valueOf();
                   $.ajax({
                        url: 'http://10.13.88.161:9000/ad/res-productline',
                        data: {
                            tags: labels,
                            from: days7,
                            to: moment().valueOf(),
                            interval: "1d"
                        },
                        timeout: 20000
                   }).done(function(json){
                        $('#seciont0-col-8').empty();
                       var id = "res-7days-productline";
                       addBox('seciont0-col-8', id, data.text + " 广告产品线统计", 1, "", "", "app");
                       var canvasid = "canvas-" + id;
                       var config = {
                            type: 'bar',
                            data: json,
                            options: {
                                title:{
                                    display:false,
                                    text:"Chart.js Bar Chart - Stacked"
                                },
                                tooltips: {
                                    mode: 'index',
                                    intersect: false
                                },
                                responsive: true,
                                scales: {
                                    xAxes: [{
                                        stacked: true,
                                    }],
                                    yAxes: [{
                                        stacked: true
                                    }]
                                }
                            }
                       };
                       var ctx = document.getElementById(canvasid).getContext("2d");
                       var handle = new Chart(ctx, config);
                   })
                   .fail(function(xhr, status, errorThrown){

                       alert("获取产品线投放信息失败" + status);
                           console.log("Error: " + errorThrown);
                           console.log("Status: " + status);
//                       $('#section0').empty();
                   });
                 }
             });
        })
        .fail(function(event){
            alert("获取数据资源分类数据出错!" + status);
                console.log("Error: " + errorThrown);
                console.log("Status: " + status);
            $('#section0').empty();
        });
   })

  /*
   *
   *  广告位查询
   */
   $('#search-adunitid-btn').click(function(event){
        console.log("but clicked");
        var adunitid = $('#search-adunitid-input').val();
        $.ajax({
            url: 'http://10.13.88.161:9000/sax/isvalidadunit',
            data: {id: adunitid},
            timeout: 20000
        })
        .done(function(data){
            if(data == "true"){
               displayAdunitinfo(adunitid);
            }else{
                alert(adunitid + " 不是有效广告位");
            }
        })
        .fail(function(xhr, status, errorThrown){
            alert("校验广告失败" + status);
                console.log("Error: " + errorThrown);
                console.log("Status: " + status);
            $('#section0').empty();
        });
        event.preventDefault();
   })
       
     $('#fy-log-query').click(function(event){
                console.log("but clicked");
                 $('#section0').empty();
                 $('#section1').empty();
                 $('#section2').empty();
                 $('#section0').append('<div class="col-md-6">' +
                                         '<h3>提交扶翼查询请求</h3>' +
                                         '<form action="/fylogquery">' +
                                             '<p><input type="text" name="logtype" id="logtype" /> 类别：exposure,click,bill</p>' +
                                             '<p><input type="text" name="from" id="from"/> 起始时间：yyyyMMdd-hhmmss,for example: 20161125-175600</p>' +
                                             '<p><input type="text" name="to" id="to"/> 结束时间：yyyyMMdd-hhmmss,for example: 20161125-175600</p>' +
                                             '<p><input type="text" name="condition" id="condition"/> 查询条件：filedname1:value1,filedname2:value2...</p>' +
                                             '<p><input type="text" name="fields" id="fields"/>	展示字段：filedname1,filedname2...</p>' +
                                             '<input id="fy-log-quey-es-bt" type="submit" value="Submit" />' +
                                         '</form>' +
                                         "<script src='@routes.Assets.versioned(\"javascripts/fylog.js\")' type=\"text/javascript\"></script>" +
                                     '</div>');

                 $('#fy-log-quey-es-bt').click(function(event){
                    var logtype = $('#logtype').val();
                    var from = $('#from').val();
                    var to = $('#to').val();
                    var condition = $('#condition').val();
                    var fields = $('#fields').val();
                    $.ajax({
                        url: "http://10.13.88.161:9000/fylogquery",
                        data: {
                            logtype: logtype,
                            from: from,
                            to: to,
                            condition: condition,
                            fields: fields,
                        },
                        timeout: 20000
                    })
                    .done(function(json){
                        var databox= $('<div class="box" style = "background-color:lightblue;color:black">' +
                                        '<div class="box-header" >' +
                                        '<h3 class="box-title">查询结果</h3>' +
                                        '</div>' +
                                        '<div class="box-body">' +
                                           json  +
                                         '</div>' +
                                         '</div>');
                        console.log(json);
                        $('#section0').append(databox);

                       // alert(json)
                    })
                    .fail(function( xhr, status, errorThrown ) {
                         alert( "扶翼查询日志失败" );
                         console.log( "Error: " + errorThrown );
                         console.log( "Status: " + status );
                         console.dir( xhr );
                    });
                    event.preventDefault();
                 })
     })
   /*
    * 联盟广告位
    */

    $('#saxmob-adunits').click(function(event){
        $('#section0').empty();
        $('#section1').empty();
        $('#section2').empty();

        //添加联盟各个广告位的曝光点击情况
        chartid = 'saxmob-allstat-chart'
        addBox('section2', chartid, "移动联盟当日投放数据概览", 1, "", "", "app");

        tableid = 'saxmob-allstat-table'
        addBox('section1', tableid, "移动联盟当日投放数据概览", 0, "", "", "app");

        $.ajax({
            url: 'http://10.13.88.161:9000/saxmob/allstat',
            data:{
                from: moment({hour: 0}).valueOf(),
                to: moment().valueOf()
            },
            timeout: 20000
        })
        .done(function(json){
            var config = {
                type: 'bar',
                data: json.chartData,
                options: {
                    responsive: true,
                    legend: {
                        position: 'top',
                    },
                    title: {
                        display: true,
                        text: '联盟广告位投放'
                    }
                }
            };
            var ctx = document.getElementById("canvas-" + chartid).getContext("2d");
            var pie = new Chart(ctx, config);

            console.log(json.tableData)
            $("#table-" + tableid).DataTable({
              data: json.tableData.data,
              "scrollX": true,
              columns: json.tableData.columns})

        })
        .fail(function( xhr, status, errorThrown ) {
             alert( "获取联盟广告位投放情况失败" );
             console.log( "Error: " + errorThrown );
             console.log( "Status: " + status );
             console.dir( xhr );
             $('#box-' + chartid).remove();
             $('#box-' + tableid).remove();
        });


        var databox = $('<div class="box panel-blur" id="fytable1">' +
                         '<div class="box-header">'+
                             '<h4 class="box-title">移动联盟广告位</h4>' +
                             '<div class="box-tools pull-right">' +
                                 '<button type="button" class="btn bg-teal btn-sm" data-widget="collapse"><i class="fa fa-minus"></i>' +
                                 '</button>' +
                                 '<button type="button" class="btn bg-teal btn-sm" data-widget="remove"><i class="fa fa-times"></i>' +
                                 '</button>' +
                             '</div>' +
                         '</div>' +
                         '<!-- /.box-header -->' +
                         '<div class="box-body">' +
                             '<table id="table-saxmob-adunits" class="table table-bordered table-striped">' +
                             '</table>' +
                         '</div>' +
                         '<!-- /.box-body -->' +
                     '</div>');
        $('#section0').append(databox);
        $.ajax({
            url: 'http://10.13.88.161:9000/adunits/saxmoball',
            dataType: 'json',
            timeout: 20000
        })
        .done(function(json){
            $('#table-saxmob-adunits').DataTable({
                data: json,
                columns: [
                    {title: "ID"},
                    {title: "名称"},
                    {title: "所属APP"},
                    {title: "开发者"},
                    {title: "资源类型"}
                ],
                "initComplete": function(){
                    var api = this.api();
                    api.$('td').click(function(){
                        api.search(this.innerHTML).draw();
                        var tr = $(this).parent('tr').first();
                        console.log(tr);
                        var tdhead = tr.children('td')[0];
                        var adunitid = tdhead.innerHTML;
                        var adunitname = tr.children('td')[1].innerHTML;
                        //添加联盟的实时数据
                        var adunitBoxId = adunitid + "-mobrt";
                        if(boxExist('box-' + adunitBoxId)){boxDisplay('box-' + adunitBoxId)} else{
                            var footer = '<div class="box-footer">' +
                                 '<div class="form-group">' +
                                     '<label>选择时间区间</label>' +
                                     '<select id="sel-'+ adunitBoxId +'" class="form-control select2" style="width: 100%;">' +
                                       '<option value=15 selected="selected">过去15m</option>' +
                                       '<option value=60>过去1h</option>' +
                                       '<option value=120>过去2h</option>' +
                                       '<option value=180>过去3h</option>' +
                                       '<option value=240>过去4h</option>' +
                                       '<option value=360>过去6h</option>' +
                                       '<option value=720>过去12h</option>' +
                                     '<option value=1440>过去1天</option>' +
                                     '<option value=2880>过去2天</option>' +
                                     '<option value=4320>过去3天</option>' +
                                     '<option value=5740>过去4天</option>' +
                                     '</select>' +
                                 '</div>' +
                            '</div>'
                            addBox("section2", adunitBoxId, adunitname + "实时投放数据", 1, footer, "", "pre");
                            $('#sel-' + adunitBoxId).select2({
                                 minimumResultsForSearch: Infinity
                            });
                            $.ajax({
                                url: 'http://10.13.88.161:9000/sax/mobstat',
                                data: {
                                    id: adunitid,
                                    from: moment().subtract(30, "m").valueOf(),
                                    to: moment().valueOf(),
                                    interval: '1m'
                                },
                                timeout: 20000,
                                dataType: 'json'
                            })
                            .done(function(json){
                                  var config = {
                                      type: 'line',
                                      data: {
                                          labels: json.labels,
                                          datasets: json.datasets,
                                      },
                                      options: {
                                          title:{
                                              text: "Chart.js Time Scale"
                                          },
                                          scales: {
                                              xAxes: [{
                                                  type: "time",
                                                  time: {
                                                      format: json.dateFormat,
                                                      // round: 'day'
                                                      tooltipFormat: 'll HH:mm'
                                                  },
                                                  scaleLabel: {
                                                      display: false,
                                                      labelString: 'Date'
                                                  },
                                                  ticks: {
                                                      fontColor: "#fff"
                                                  }
                                              }, ],
                                              yAxes: [{
                                                  scaleLabel: {
                                                      display: false,
                                                      labelString: 'value'
                                                  },
                                                  ticks: {
                                                      fontColor: "#fff"
                                                  }
                                              }]
                                          },
                                          responsive: true,
                                          fontColor: '#fff',
                                          tooltips: {
                                              position: 'average',
                                              mode: 'index',
                                              intersect: false,
                                          }
                                      }
                                  };
                                  var ctx = document.getElementById("canvas-" + adunitBoxId).getContext("2d");
                                  var handle = new Chart(ctx, config);

                                  $('#sel-' + adunitBoxId).on("select2:select", function (e) {

                                      var t = $(this).val();
                                      var from = moment().subtract(t, "m").valueOf();
                                      var inter = getinverval(t);
                                      $.ajax({
                                          url: 'http://10.13.88.161:9000/sax/mobstat',
                                          data: {
                                              id: adunitid,
                                              from: from,
                                              to: moment().valueOf(),
                                              interval: inter
                                          },
                                          timeout: 20000,
                                          dataType: 'json'
                                      }).done(function(json){
                                          config.data.datasets = json.datasets;
                                          handle.update();
                                      })
                                       .fail(function( xhr, status, errorThrown ) {
                                            alert( "获取联盟广告投放情况失败" );
                                            console.log( "Error: " + errorThrown );
                                            console.log( "Status: " + status );
                                            console.dir( xhr );
                                       });

                                  }); //sel

                            })
                            .fail(function( xhr, status, errorThrown ) {
                                 alert( "获取联盟广告位投放情况失败" );
                                 console.log( "Error: " + errorThrown );
                                 console.log( "Status: " + status );
                                 console.dir( xhr );
                            });

                        }
                    });
                }
            });
        })
        .fail(function(xhr, status, errorThrown){
           alert("获取移动联盟广告位信息出错" + status);
           console.log("Error: " + errorThrown);
           console.log("Status: " + status);
       });
    })


   /*
    * 各个APP的统计信息
    *
    */

    $('#news-app').click(function(event){
        var id = 'news-app-chart';
        $('#section0').empty();
        $('#section1').empty();
        $('#section2').empty();
        var boxid = 'box-' + id;
        if(boxExist(boxid)){boxDisplay(boxid);}else{
            addBox("section1", id, "新闻APP客户端分类统计", 2, "", "", "app");
            $.ajax({
                url: "http://10.13.88.161:9000/sax/newsappinfo",
                timeout: 20000,
                dataType: 'json'
            })
            .done(function(json){
                Highcharts.chart('hicharts-' + id, {
                    chart: {
                      type: 'pie'
                    },
                    title: {
                      text: '新闻APP客户端操作系统信息统计'
                    },
                    subtitle: {
                      text: '点击切片查看操作系统版本号信息'
                    },
                    plotOptions: {
                      series: {
                        dataLabels: {
                          enabled: true,
                          format: '{point.name}: {point.y}'
                        }
                      }
                    },

                    tooltip: {
                      headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
                      pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y}</b> of total<br/>'
                    },
                    series: json.series,
                    drilldown: json.drilldown
                  });
            })
            .fail(function(xhr, status, errorThrown){
                alert("获取APP信息错误" + status);
                    console.log("Error: " + errorThrown);
                    console.log("Status: " + status);
                $('#section0').empty();
            });

        }

        var verid = 'news-appver-chart';
        var verboxid = 'box-' + verid;
        if(boxExist(verboxid)){boxDisplay(verboxid);}else{
            addBox("section2", verid, "新闻APP版本分类统计", 2, "", "", "app");
            $.ajax({
                url: "http://10.13.88.161:9000/sax/appinfo",
                data: {app: "app:com.sina.news, 299853944"},
                timeout: 20000,
                dataType: 'json'
            })
            .done(function(json){
                Highcharts.chart('hicharts-' + verid, {
                    chart: {
                      type: 'pie'
                    },
                    title: {
                      text: '新闻APP客户端版本分类统计'
                    },
                    subtitle: {
                      text: '点击切片查看新闻APP版本号信息'
                    },
                    plotOptions: {
                      series: {
                        dataLabels: {
                          enabled: true,
                          format: '{point.name}: {point.y}'
                        }
                      }
                    },

                    tooltip: {
                      headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
                      pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y}</b> of total<br/>'
                    },
                    series: json.series,
                    drilldown: json.drilldown
                  });
            })
            .fail(function(xhr, status, errorThrown){
                alert("获取APP版本信息错误" + status);
                    console.log("Error: " + errorThrown);
                    console.log("Status: " + status);
                $('#section0').empty();
            });
        }
    })


   /*
    * 广告调试平台
    */
    $('#engin-rt-debug-log').click(function(event){
        $('#section0').empty();
        $('#section1').empty();
        $('#section2').empty();

        var id = 'engine-rt-debug-log'
        var boxid = "box-" + id

        addBox('section0', id, "广告请求数据", 0, "", "", "app");
        $.ajax({
            url: 'http://10.13.88.161:9000/addebug/reqinfo',
            timeout: 20000
        })
        .done(function(json){
           console.log(json)
           $('#table-' + id).DataTable({
                data: json.data,
                "scrollX": true,
                columns: json.columns,
                "initComplete": function(){
                    var api = this.api();
                    api.$('td').click(function(){
                        api.search(this.innerHTML).draw();
                        var tr = $(this).parent('tr').first();
                        var tdhead = tr.children('td')[3];
                        var hashcode = tdhead.innerHTML;
                        var adunitid = tr.children('td')[2].innerHTML;
                        console.log("调试 click first is" + hashcode);
                        $('.timeline').remove();
                        $.ajax({
                            url: 'http://10.13.88.161:9000/addebug/deliverinfo',
                            data: {hashcode: hashcode, adunitid: adunitid},
                            timeout: 20000
                        })
                        .done(function(json){
                            console.log(json)
                           var url = '<url class="timeline">' + adreq(json.adreqinfo);

                           for(var i in json.deliverinfo){
                                url += timelineRange(json.deliverinfo[i]);
                           }
                           url += adrsp(json.adrspinfo);

                           console.log(url)
                           $('#section0').append('</url>' + url + '</url>')

                        })
                        .fail(function(xhr, status, errorThrown){
                            alert("获取投放信息错误" + status);
                                console.log("Error: " + errorThrown);
                                console.log("Status: " + status);
                        });
                    })
                }
           })
        })
        .fail(function(xhr, status, errorThrown){
            alert("获取广告请求信息错误" + status);
                console.log("Error: " + errorThrown);
                console.log("Status: " + status);
            $('#section0').empty();
        });
    })


    setMovBox();

});

//data:{label: String, items:{time: String, title: String, content: String}}

function timelineRange(data) {
    console.log(data);
    var timelabel = '<li class="time-label">' +
        '<span class="bg-red">' +
            data.label +
        '</span>' +
    '</li>'

    for(var i in data.items) {
       var item = data.items[i];
       timelabel += '<li>' +
            '<!-- timeline icon -->' +
            '<i class="fa fa-envelope bg-blue"></i>' +
            '<div class="timeline-item">' +
                '<span class="time"><i class="fa fa-clock-o"></i>' + item.time + '</span>' +
                '<h3 class="timeline-header">'+ item.title +'</h3>' +
                '<div class="timeline-body">' +
                    item.content +
                '</div>' +
            '</div>' +
        '</li>'
    }
    return timelabel
}

// adreq {label: String, time: String, title: String, pageurl: String, reqline: String, adunits: [String]}
function adreq(data) {
    var timelabel =
    '<li class="time-label">' +
        '<span class="bg-red">' +
            data.label +
        '</span>' +
    '</li>' +
    '<li>' +
        '<!-- timeline icon -->' +
        '<i class="fa fa-envelope bg-blue"></i>' +
        '<div class="timeline-item">' +
            '<span class="time"><i class="fa fa-clock-o"></i>' + data.time + '</span>' +
            '<h3 class="timeline-header">'+ data.title +'</h3>' +
            '<div class="timeline-body">' +
                '<a href="' + data.pageurl+ '" target="_blank">页面url: ' + data.pageurl +'</a>' +
                '<div>'+ data.reqline +'</div>' +
                '<div>广告位: '+ data.adunits.join(',') +'</div>' +
            '</div>' +
        '</div>' +
    '</li>'
    return timelabel
}

// adreq {label: String, time: String, title: String, adunits: [{id: String, title: String, intro: String, image: [String]}]}
function adrsp(data) {
    console.log("adsp");
    console.log(data);
    var images = ""

    for(i in data.adunits){
        var adunitad = data.adunits[i];
        images +=  '<div>' +
            '<p>' + adunitad.id + '</p>' +
             '<p>' + adunitad.title + '</p>' +
             '<p>' + adunitad.intro + '</p>' +
             '<img src='+ adunitad.image[0] +' class="margin" width="100px">' +
        '</div>'
    }

    var timelabel =
    '<li class="time-label">' +
        '<span class="bg-red">' +
            data.label +
        '</span>' +
    '</li>' +
    '<li>' +
        '<!-- timeline icon -->' +
        '<i class="fa fa-envelope bg-blue"></i>' +
        '<div class="timeline-item">' +
            '<span class="time"><i class="fa fa-clock-o"></i>' + data.time + '</span>' +
            '<h3 class="timeline-header">'+ data.title +'</h3>' +
            '<div class="timeline-body">' +
                images +
            '</div>' +
        '</div>' +
    '</li>'
    return timelabel
}


/*
 * 判断box with id 是否已经存在
 */
function boxExist(id){
    if($('#' + id).length){
        console.log(id + "exist");
        return true;
    }else{
        console.log(id + "not exist");
        return false;
    }
}

function boxDisplay(id){
    $("#" + id).css("display", "block");
}

/*
* id  用来进行设置boxid  chart id  or table id
* bodytype  0 table  1 chart 3 uk
*  table 中会添加一个box-sub+id 的一个div  用来进行添加其他的一些元素
*/
function addBox(sectionid, id, title, bodytype, footer, contenthead, pos){
    var content = ""
    var ratio = ""
    if(browser.versions.mobile){
        ratio = 'width="200" height="400"'
    }else{
        ratio = 'width="300" height="200"'
    }
    if(bodytype == 0){
        content = '<div class="row">'
          + '<table id="table-'+ id +'" class="table table-bordered table-striped">' +'</table>' 
          + '</div>'
          + '<div class="row" id="box-sub-' + id + '"></div>' 
    }else if(bodytype == 1){
        content = '<div class="chart">' +
             '<canvas id="canvas-'+ id +'" '+ ratio +' style="height: 400px;"></canvas>' +
         '</div>';
    }else if(bodytype == 2){
        content = '<div id="hicharts-'+ id +'" style="min-width: 310px; max-width: 600px; height: 400px; margin: 0 auto"></div>';
    }else if(bodytype == 3){
        content = '<div class="chart">' +
             '<canvas id="canvas-'+ id +'" '+ ratio +'></canvas>' +
         '</div>';
    }

    var databox = $('<div class="box panel-blur" id="box-'+ id +'">' +
           '<div class="box-header">'+
               '<h3 class="box-title">'+ title +'</h3>' +
               '<div class="box-tools pull-right">' +
                   '<button type="button" class="btn bg-teal btn-sm" data-widget="collapse"><i class="fa fa-minus"></i>' +
                   '</button>' +
                   '<button type="button" class="btn bg-teal btn-sm" data-widget="remove"><i class="fa fa-times"></i>' +
                   '</button>' +
               '</div>' +
           '</div>' +
           '<!-- /.box-header -->' +
           '<div class="box-body">' +
               contenthead + content +
           '</div>' +
           '<!-- /.box-body -->' +
           footer +
       '</div>');
    if(pos == "app"){
        console.log("app");
        $('#' + sectionid).append(databox);
    }if(pos == "pre"){
        console.log('pre');
        $('#' + sectionid).prepend(databox);
    }

}



function setMovBox(){
      //Make the dashboard widgets sortable Using jquery UI
      // $(".connectedSortable").sortable({
      //   placeholder: "sort-highlight",
      //   connectWith: ".connectedSortable",
      //   handle: ".box-header, .nav-tabs",
      //   forcePlaceholderSize: true,
      //   zIndex: 999999
      // });
      // $(".connectedSortable .box-header, .connectedSortable .nav-tabs-custom").css("cursor", "move");

}

function make_chartjs_graph(chart_canvas_id, legend_id, dataset_config) {
        var get_display_datasets = function(datasets) {
        var final_datasets = new Array();
        $.each(datasets, function(index, value) {
          if (value) {
              final_datasets.push(value);
          };
          });
          return final_datasets;
        };

        var y_datasets = get_display_datasets(dataset_config.datasets);

        var chart = $('#' + chart_canvas_id);
        var legend = $('#' + legend_id);
        var lineChartData = dataset_config;

        var lineChartOptions = {
           //Boolean - If we should show the scale at all
           showScale: true,
           //Boolean - Whether grid lines are shown across the chart
           scaleShowGridLines: true,
           //String - Colour of the grid lines
           scaleGridLineColor: "rgba(255,255,255,1)",
           //String - Scale label font colour
           scaleFontColor : "#fff",
           //Number - Width of the grid lines
           scaleGridLineWidth: 1,
           //Boolean - Whether to show horizontal lines (except X axis)
           scaleShowHorizontalLines: true,
           //Boolean - Whether to show vertical lines (except Y axis)
           scaleShowVerticalLines: true,
           //Boolean - Whether the line is curved between points
           bezierCurve: true,
           //Number - Tension of the bezier curve between points
           bezierCurveTension: 0.3,
           //Boolean - Whether to show a dot for each point
           pointDot: true,
           //Number - Radius of each point dot in pixels
           pointDotRadius: 4,
           //Number - Pixel width of point dot stroke
           pointDotStrokeWidth: 1,
           //Number - amount extra to add to the radius to cater for hit detection outside the drawn point
           pointHitDetectionRadius: 20,
           //Boolean - Whether to show a stroke for datasets
           datasetStroke: true,
           //Number - Pixel width of dataset stroke
           datasetStrokeWidth: 2,
           //Boolean - Whether to fill the dataset with a color
           datasetFill: false,
           //Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
           maintainAspectRatio: true,
           //Boolean - whether to make the chart responsive to window resizing
           responsive: true,
           multiTooltipTemplate: "<%if (datasetLabel){%><%=datasetLabel%>: <%}%><%= value %>"
        };

         var lineChartCanvas = chart.get(0).getContext("2d");
         var lineChart = new Chart(lineChartCanvas);
         var line_chart_handle = lineChart.Line(lineChartData, lineChartOptions);


         var div_checks = $('<div class="col-xs-8">');
         $.each(y_datasets, function(index, value) {
           var div_li = $('<label class="checkbox-inline"><input type="checkbox" name="' + accountid  + '" value="' + index + '">' + value.label + '</label>');
           div_checks.append(div_li);
         });

         legend.empty();
         legend.append(div_checks);

         $('[name = ' + accountid + ']:checkbox').each(function(key, value) {
               $(this).attr('checked', true);
               $(this).on('', function (e, data) {
                   var $el = $(data.el)
                     , value = data.value;
                   console.log(e, $el, value);
               });

               $(this).change(function() {
                       var index = $(this).attr('value');
                       if ($(this).is(':checked')) {
                          $.each(y_datasets[index].data, function(key, value) {
                            line_chart_handle.datasets[index].points.push(new line_chart_handle.PointClass({
                              value : value,
                              label : lineChartData.labels[key],
                              datasetLabel : lineChartData.datasets[index].label,
                              x: line_chart_handle.scale.calculateX(line_chart_handle.scale.valuesCount + 1),
                              y: line_chart_handle.scale.endPoint,
                              strokeColor : line_chart_handle.datasets[index].pointStrokeColor,
                              fillColor : line_chart_handle.datasets[index].pointColor
                            }));
                          });
                        } else {
                          for (var i = line_chart_handle.datasets[index].points.length - 1; i >= 0; i--) {
                            line_chart_handle.datasets[index].points.shift();
                          }
                        }

                      line_chart_handle.update();
                    });
              });
            };

function time(t){
    if(t == "now-15m"){
        return moment().subtract(t, "m").valueOf();
    }
}

function getinverval(t){
    if(t<=120){
        return "1m";
    } else if(t<=360){
        return "5m";
    } else {
        return "10m";
    }
}

function displayAdunitinfo(id){
    var adunitid = id;
    var adunitname = "I do not known"

    //添加扶翼的实时投放数据
    var adunitBoxId = adunitid + "-rt";

    $('#section1').empty();
    $('#section2').empty();
    if(boxExist('box-' + adunitBoxId)){boxDisplay('box-' + adunitBoxId);}else{
        var adunitinfomodal = "<p>" + adunitname +"</p>" +
        '<!-- Button trigger modal -->' +
        '<button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#'+adunitid+'-Modal">' +
          '管理端配置' +
        '</button>' +
        '<!-- Modal -->' +
        '<div class="modal fade" id="'+adunitid+'-Modal" tabindex="-1" role="dialog" aria-labelledby="'+ adunitid +'-ModalLabel">' +
          '<div class="modal-dialog" role="document">' +
            '<div class="modal-content">' +
              '<div class="modal-header">' +
                '<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>' +
                '<h4 class="modal-title" id="'+ adunitid +'-ModalLabel">'+ adunitname +'</h4>' +
              '</div>' +
              '<div class="modal-body">' +

              '</div>' +
            '</div>' +
          '</div>' +
        '</div>'
        var footer = '<div class="box-footer">' +
             '<div class="form-group">' +
                 '<label>选择时间区间</label>' +
                 '<select id="sel-'+ adunitBoxId +'" class="form-control select2" style="width: 100%;">' +
                   '<option value=15 selected="selected">过去15m</option>' +
                   '<option value=60>过去1h</option>' +
                   '<option value=120>过去2h</option>' +
                   '<option value=180>过去3h</option>' +
                   '<option value=240>过去4h</option>' +
                   '<option value=360>过去6h</option>' +
                   '<option value=720>过去12h</option>' +
                   '<option value=1440>过去1天</option>' +
                   '<option value=2880>过去2天</option>' +
                   '<option value=4320>过去3天</option>' +
                   '<option value=5740>过去4天</option>' +
                 '</select>' +
             '</div>' +
        '</div>'
        addBox("section1", adunitBoxId, adunitid + "实时投放数据", 1, footer, adunitinfomodal, "pre");
        $('#sel-' + adunitBoxId).select2({
             minimumResultsForSearch: Infinity
        });
        $('#' + adunitid + '-Modal').on('show.bs.modal', function (event) {
          //var button = $(event.relatedTarget) // Button that triggered the modal
          //var recipient = button.data('whatever') // Extract info from data-* attributes
          // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
          // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
          var modal = $(this)
          //modal.find('.modal-title').text('New message to ' + recipient)
          modal.find('.modal-body').html("<p>查询数据。。</p>");
          $.ajax({
            url: "http://10.13.88.161:9000/adunitconfiginfo",
            data: {id: adunitid},
            timeout: 20000,
            dataType: "text"
          })
          .done(function(data){
            console.log(data);
            modal.find('.modal-body').html(data);
          })
          .fail(function( xhr, status, errorThrown ) {
               alert( "获取广告位配置信息失败" );
               console.log( "Error: " + errorThrown );
               console.log( "Status: " + status );
               console.dir( xhr );
             })
        })

        $('#exampleModal').on('show.bs.modal', function (event) {
          var button = $(event.relatedTarget) // Button that triggered the modal
          var recipient = button.data('whatever') // Extract info from data-* attributes
          // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
          // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
          var modal = $(this)
          modal.find('.modal-title').text('New message to ' + recipient)
          modal.find('.modal-body input').val(recipient)
        })

        $.ajax({
            url: "http://10.13.88.161:9000/sax/adunitrt",
            data: {
                adunitid: adunitid,
                interval: "15m",
                from: moment().subtract(30, "m").valueOf(),
                to: moment().valueOf()
            },
            timeout: 20000,
            dataType: "json",
        })
        .done(function(json){
            var config = {
                type: 'line',
                data: {
                    labels: json.labels,
                    datasets: json.datasets,
                },
                options: {
                    title:{
                        text: "Chart.js Time Scale"
                    },
                    scales: {
                        xAxes: [{
                            type: "time",
                            time: {
                                format: json.dateFormat,
                                // round: 'day'
                                tooltipFormat: 'll HH:mm'
                            },
                            scaleLabel: {
                                display: false,
                                labelString: 'Date'
                            },
                            ticks: {
                                fontColor: "#fff"
                            }
                        }, ],
                        yAxes: [{
                            scaleLabel: {
                                display: false,
                                labelString: 'value'
                            },
                            ticks: {
                                fontColor: "#fff"
                            }
                        }]
                    },
                    responsive: true,
                    fontColor: '#fff',
                    tooltips: {
                        position: 'average',
                        mode: 'index',
                        intersect: false,
                    }
                }
            };
            var ctx = document.getElementById("canvas-" + adunitBoxId).getContext("2d");
            var handle = new Chart(ctx, config);

            $('#sel-' + adunitBoxId).on("select2:select", function (e) {

                var t = $(this).val();
                var from = moment().subtract(t, "m").valueOf();
                var inter = getinverval(t);
                $.ajax({
                    url: 'http://10.13.88.161:9000/sax/adunitrt',
                    data: {
                        adunitid, adunitid,
                        from: from,
                        to: moment().valueOf(),
                        interval: "15m"
                    },
                    timeout: 20000,
                    dataType: 'json'
                }).done(function(json){
                    config.data.datasets = json.datasets;
                    handle.update();
                })
                 .fail(function( xhr, status, errorThrown ) {
                      alert( "获取扶翼广告投放情况失败" );
                      console.log( "Error: " + errorThrown );
                      console.log( "Status: " + status );
                      console.dir( xhr );
                 });

            });
        });
    }


    //添加引擎级别的实时投放数据
    var adunitEngineBoxid = adunitid + '-eng-line';
    if(boxExist('box-' + adunitEngineBoxid)){boxDisplay('box-' + adunitEngineBoxid);} else{
        var footer = '<div class="box-footer">' +
                 '<div class="form-group">' +
                     '<label>选择时间区间</label>' +
                     '<select id="sel-'+ adunitEngineBoxid +'" class="form-control select2" style="width: 100%;">' +
                       '<option value=15 selected="selected">过去15m</option>' +
                       '<option value=60>过去1h</option>' +
                       '<option value=120>过去2h</option>' +
                       '<option value=180>过去3h</option>' +
                       '<option value=240>过去4h</option>' +
                       '<option value=360>过去6h</option>' +
                       '<option value=720>过去12h</option>' +
                      '<option value=1440>过去1天</option>' +
                      '<option value=2880>过去2天</option>' +
                      '<option value=4320>过去3天</option>' +
                      '<option value=5740>过去4天</option>' +
                     '</select>' +
                 '</div>' +
            '</div>'
        addBox("section2", adunitEngineBoxid, adunitid + "引擎层级广告数据", 1, footer, "", "pre");
        $('#sel-' + adunitEngineBoxid).select2({
             minimumResultsForSearch: Infinity
        });
        $.ajax({
            url: 'http://10.13.88.161:9000/sax/adunitenginedeliverinfo',
            data: {
                adunitid: adunitid,
                interval: "1m",
                from: moment().subtract(30, "m").valueOf(),
                to: moment().valueOf()
            },
            timeout: 20000,
            dataType: 'json'
        })
        .done(function(json){
            var config = {
                type: 'line',
                data: {
                    labels: json.labels,
                    datasets: json.datasets,
                },
                options: {
                    title:{
                        text: "Chart.js Time Scale"
                    },
                    scales: {
                        xAxes: [{
                            type: "time",
                            time: {
                                format: json.dateFormat,
                                // round: 'day'
                                tooltipFormat: 'll HH:mm'
                            },
                            scaleLabel: {
                                display: false,
                                labelString: 'Date'
                            },
                            ticks: {
                                fontColor: "#fff"
                            }
                        }, ],
                        yAxes: [{
                            scaleLabel: {
                                display: false,
                                labelString: 'value'
                            },
                            ticks: {
                                fontColor: "#fff"
                            }
                        }]
                    },
                    responsive: true,
                    fontColor: '#fff',
                    tooltips: {
                        position: 'average',
                        mode: 'index',
                        intersect: false,
                    }
                }
            };
            var ctx = document.getElementById("canvas-" + adunitEngineBoxid).getContext("2d");
            var handle = new Chart(ctx, config);

            $('#sel-' + adunitEngineBoxid).on("select2:select", function (e) {

                var t = $(this).val();
                var from = moment().subtract(t, "m").valueOf();
                var inter = getinverval(t);
                $.ajax({
                    url: 'http://10.13.88.161:9000/sax/adunitenginedeliverinfo',
                    data: {
                        adunitid, adunitid,
                        from: from,
                        to: moment().valueOf(),
                        interval: inter
                    },
                    timeout: 20000,
                    dataType: 'json'
                }).done(function(json){
                    config.data.datasets = json.datasets;
                    handle.update();
                })
                 .fail(function( xhr, status, errorThrown ) {
                      alert( "获取引擎级别广告投放情况失败" );
                      console.log( "Error: " + errorThrown );
                      console.log( "Status: " + status );
                      console.dir( xhr );
                 });

            });
        })
       .fail(function( xhr, status, errorThrown ) {
          alert( "获取广告位各个产品线广告投放情况失败" );
          console.log( "Error: " + errorThrown );
          console.log( "Status: " + status );
          console.dir( xhr );
        })
    }

    //添加产品线的实时投放数据
    var adunitProductLineBoxid = adunitid + '-product-line';
    if(boxExist('box-' + adunitProductLineBoxid)){boxDisplay('box-' + adunitProductLineBoxid);} else{
        var footer = '<div class="box-footer">' +
             '<div class="form-group">' +
                 '<label>选择时间区间</label>' +
                 '<select id="sel-'+ adunitProductLineBoxid +'" class="form-control select2" style="width: 100%;">' +
                   '<option value=15 selected="selected">过去15m</option>' +
                   '<option value=60>过去1h</option>' +
                   '<option value=120>过去2h</option>' +
                   '<option value=180>过去3h</option>' +
                   '<option value=240>过去4h</option>' +
                   '<option value=360>过去6h</option>' +
                   '<option value=720>过去12h</option>' +
                  '<option value=1440>过去1天</option>' +
                  '<option value=2880>过去2天</option>' +
                  '<option value=4320>过去3天</option>' +
                  '<option value=5740>过去4天</option>' +
                 '</select>' +
             '</div>' +
        '</div>'
        addBox("section2", adunitProductLineBoxid, adunitid + "产品线广告数据", 1, footer, "", "app");
        $('#sel-' + adunitProductLineBoxid).select2({
             minimumResultsForSearch: Infinity
        });
        $.ajax({
            url: 'http://10.13.88.161:9000/sax/adunitproductline',
            data: {
                adunitid: adunitid,
                interval: "1m",
                from: moment().subtract(30, "m").valueOf(),
                to: moment().valueOf()
            },
            timeout: 20000,
            dataType: 'json'
        })
        .done(function(json){
            var config = {
                type: 'line',
                data: {
                    labels: json.labels,
                    datasets: json.datasets,
                },
                options: {
                    title:{
                        text: "Chart.js Time Scale"
                    },
                    scales: {
                        xAxes: [{
                            type: "time",
                            time: {
                                format: json.dateFormat,
                                // round: 'day'
                                tooltipFormat: 'll HH:mm'
                            },
                            scaleLabel: {
                                display: false,
                                labelString: 'Date'
                            },
                            ticks: {
                                fontColor: "#fff"
                            }
                        }, ],
                        yAxes: [{
                            scaleLabel: {
                                display: false,
                                labelString: 'value'
                            },
                            ticks: {
                                fontColor: "#fff"
                            }
                        }]
                    },
                    responsive: true,
                    fontColor: '#fff',
                    tooltips: {
                        position: 'average',
                        mode: 'index',
                        intersect: false,
                    }
                }
            };
            var ctx = document.getElementById("canvas-" + adunitProductLineBoxid).getContext("2d");
            var handle = new Chart(ctx, config);
            $('#sel-' + adunitEngineBoxid).on("select2:select", function (e) {

                var t = $(this).val();
                var from = moment().subtract(t, "m").valueOf();
                var inter = getinverval(t);
                $.ajax({
                    url: 'http://10.13.88.161:9000/sax/adunitproductline',
                    data: {
                        adunitid, adunitid,
                        from: from,
                        to: moment().valueOf(),
                        interval: inter
                    },
                    timeout: 20000,
                    dataType: 'json'
                }).done(function(json){
                    config.data.datasets = json.datasets;
                    handle.update();
                })
                 .fail(function( xhr, status, errorThrown ) {
                      alert( "获取展示引擎产品线广告投放情况失败" );
                      console.log( "Error: " + errorThrown );
                      console.log( "Status: " + status );
                      console.dir( xhr );
                 });

            });

        })
       .fail(function( xhr, status, errorThrown ) {
          alert( "获取广告位各个产品线广告投放情况失败" );
          console.log( "Error: " + errorThrown );
          console.log( "Status: " + status );
          console.dir( xhr );
        })
    }

}
